package cn.copera.kaka.controller;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletInputStream;

import org.apache.log4j.Logger;

import cn.copera.kaka.bean.InMessage;
import cn.copera.kaka.bean.OutMessage;
import cn.copera.kaka.bean.ScanCodeInfo;
import cn.copera.kaka.bean.TextOutMessage;
import cn.copera.kaka.model.Check;
import cn.copera.kaka.model.ExchangeRecord;
import cn.copera.kaka.model.ExchangeRule;
import cn.copera.kaka.model.Log;
import cn.copera.kaka.model.Order;
import cn.copera.kaka.model.Praise;
import cn.copera.kaka.model.Report;
import cn.copera.kaka.model.Shop;
import cn.copera.kaka.model.ShopImage;
import cn.copera.kaka.model.Track;
import cn.copera.kaka.model.User;
import cn.copera.kaka.model.UserShop;
import cn.copera.kaka.utils.ProjectConfig;
import cn.copera.kaka.utils.Sign;
import cn.copera.kaka.utils.WxUtils;
import cn.copera.kaka.utils.XStreamFactory;
import cn.copera.kaka.vo.footPrintVo;
import cn.copera.kaka.wx.handler.MessageProcessingHandler;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.jfinal.core.ActionKey;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Page;
import com.qq.weixin.mp.aes.WXBizMsgCrypt;
import com.thoughtworks.xstream.XStream;

/**
 * CommonController
 */
public class CommonController extends Controller {

	private final Logger logger = Logger.getLogger(CommonController.class);
	
	private static final String RANDOM_CODE_KEY = "1";
	
    public static String getServer(){
    	ProjectConfig config = new ProjectConfig();
    	return config.getServetURL();
    }

	public void index() {
		render("/common/login.jsp");
	}
	
	public void loginUI() {
		render("/common/login.jsp");
	}	
	
	// 举报
	public void report() {
		String shopId = getPara(0);
		String openid = getPara(1);
		Shop shop = Shop.dao.findById(shopId);
		setAttr("openid", openid);
		setAttr("shop", shop);
		setAttr("shopid", shopId);
		setAttr("serverUrl", getServer());
		render("/report.jsp");
	}

	public void reportSave() throws UnsupportedEncodingException{
		String shopId = getPara(0);
		String openid = getPara(1);
		String number = URLDecoder.decode(getPara(2), "UTF-8");
		String right = "";
		String type ="";
		int kadian=5;
		UserShop us = UserShop.dao.findFirst("select * from ka_user_shop where openid=? and shop_id=?",openid,shopId);
		Order order = Order.dao.findFirst("select * from ka_order where openid=? and shop_id=?",openid,shopId);
		if(number!=null  && !number.trim().equals("")){
		if(number.equals("0")){
			right="sexy";
			type="举报";
			setAttr("message", "举报成功，卡卡将核实您的消息");
		}else if(number.equals("1")){
			right = "sensitive";
			type="举报";
			setAttr("message", "举报成功，卡卡将核实您的消息");
		}else if(number.equals("2")){
			right = "false";
			type="举报";
			setAttr("message", "举报成功，卡卡将核实您的消息");
		}else if(number.equals("3")){
			right = "infri";
			type="举报";
			setAttr("message", "举报成功，卡卡将核实您的消息");
		}else{
			right = number;
			type="建议";
			setAttr("message", "感谢您的建议，本店将据此提高服务质量（每月一次建议）");
		}
//		if(type.equals("建议")){
//			if(us.getTimestamp("report_time")!=null){
//				  SimpleDateFormat format1 = new SimpleDateFormat("M"); 
//				  Date d = new Date();
//				  String date = format1.format(d);		
//				  String date1 = format1.format(us.getTimestamp("report_time"));	
//				  if(!date.equals(date1)){
//						us.set("report_time", new Date()).update();
//						Shop shop = Shop.dao.findById(shopId);
//						Date date2 = new Date();
//				        Calendar cal = Calendar.getInstance();
//				        cal.setTime(date2);
//				        cal.add(Calendar.MONTH, Integer.parseInt(shop.getStr("valid_date")));
//						Track track = new Track();
//						DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
//						track.set("id", System.currentTimeMillis() + "").set("nick_name", openid).set("create_date", new Date()).set("del_flag", "0").set("update_date", new Date()).set("create_date_str", format.format(new Date())).set("state", "0").set("count", kadian).set("usable_count", kadian).set("shop_id", shopId).set("valid_date", cal.getTime()).set("remarks", "提供建议，获赠5个卡点").set("create_name", "我自己").save();
//						if(order!=null){
//						order.set("time", new Date()).update();
//						}
//						getModel(Report.class).set("shop_id", shopId).set("openid", openid).set("detail", right).set("id", System.currentTimeMillis() + "").set("del_flag", "0").set("create_date", new Date()).set("type", type).save();								
//				  }else{
//					  setAttr("message", "感谢您的建议，欢迎下个月继续提供建议");  
//				  }				
//			}else{
//				us.set("report_time", new Date()).update();
//				Shop shop = Shop.dao.findById(shopId);
//				Date date = new Date();
//		        Calendar cal = Calendar.getInstance();
//		        cal.setTime(date);
//		        cal.add(Calendar.MONTH, Integer.parseInt(shop.getStr("valid_date")));
//				Track track = new Track();
//				DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
//				track.set("id", System.currentTimeMillis() + "").set("nick_name", openid).set("create_date", new Date()).set("del_flag", "0").set("update_date", new Date()).set("create_date_str", format.format(new Date())).set("state", "0").set("count", kadian).set("usable_count", kadian).set("shop_id", shopId).set("valid_date", cal.getTime()).set("remarks", "提供建议，获赠5个卡点").set("create_name", "我自己").save();
//				if(order!=null){
//				order.set("time", new Date()).update();
//				}
//				getModel(Report.class).set("shop_id", shopId).set("openid", openid).set("detail", right).set("id", System.currentTimeMillis() + "").set("del_flag", "0").set("create_date", new Date()).set("type", type).save();						
//			}
//		}
		getModel(Report.class).set("shop_id", shopId).set("openid", openid).set("detail", right).set("id", System.currentTimeMillis() + "").set("del_flag", "0").set("create_date", new Date()).set("type", type).save();								
		}
		forwardAction("/shopIndex/"+shopId+"-"+openid+"-"+type);
	}
	
	// 分享
	@ActionKey("/share")
	public void share() throws Exception {
		String shopId = getPara(0);
		String openid = getPara(1);
		String message = getPara(2);
		Shop shop = Shop.dao.findById(shopId);
		Praise s = Praise.dao.findFirst("select * from ka_pointpraise_set where shop_id=? and type=?",shopId,"分享");
		UserShop us = UserShop.dao.findFirst("select * from ka_user_shop where openid=? and shop_id=?",openid,shopId);
		SimpleDateFormat format = new SimpleDateFormat("d"); 
		Date d = new Date();
		String date = format.format(d);	
		if(us!=null && us.getStr("share_time")!=null){
		if(us.getStr("share_time").equals(date)){
		}else{
			us.set("day_share_count", 0).update();
		}
		}
		if(s!=null && s.getInt("total_count")!=null && us.getInt("share_count")!=null && s.getInt("presenter_count")!=null){
		int check = us.getInt("share_count")/s.getInt("total_count")*s.getInt("presenter_count");
		setAttr("check", check);		
		}
		setAttr("share", s);
		setAttr("shop", shop);
		setAttr("shopid", shopId);
		setAttr("openid", openid);
		setSessionAttr("shopid", shopId);
		setSessionAttr("openid", openid);
		setSessionAttr("serverUrl", getServer());
		setSessionAttr("shopname", shop.getStr("shop_name"));
		setSessionAttr("shopimage", shop.getStr("head_image"));		
//		String accessToken =WxUtils. getAccessToken(WxUtils.APPID, WxUtils.APPSECRET);
//		String jsapi_ticket = WxUtils.getJsapi_ticket(accessToken);
//		String url = "http://dyywx.shijun.org/kakawx/share/"+shopId+"-"+openid;
//		Map<String, String> ret = Sign.sign(jsapi_ticket,url);
//		setAttr("url", ret.get("url"));
//		setAttr("signature", ret.get("signature"));
//		setAttr("nonceStr", ret.get("nonceStr"));
//		setAttr("timestamp", ret.get("timestamp"));
//		System.out.println("signature:"+ret.get("signature"));
//		System.out.println("nonceStr:"+ret.get("nonceStr"));
//		System.out.println("timestamp:"+ret.get("timestamp"));
//		System.out.println("url:"+ret.get("url"));
		setAttr("us", us);
		setAttr("serverUrl", getServer());
		setAttr("message", message);
		render("/share.jsp");
	}

	// 点赞
	@ActionKey("/praise")
	public void praise() {
		String shopId = getPara(0);
		String openid = getPara(1);
		String message = getPara(2);
		Shop shop = Shop.dao.findById(shopId);
		Praise p = Praise.dao.findFirst("select * from ka_pointpraise_set where shop_id=? and type=?",shopId,"点赞");
		UserShop us = UserShop.dao.findFirst("select * from ka_user_shop where openid=? and shop_id=?",openid,shopId);
		SimpleDateFormat format = new SimpleDateFormat("d"); 
		Date d = new Date();
		String date = format.format(d);	
		if(us!=null && us.getStr("praise_time")!=null){
		if(us.getStr("praise_time").equals(date)){
		}else{
			us.set("day_praise_count", 0).update();
		}		
		}
		if(p!=null && p.getInt("total_count")!=null && us.getInt("point_praise_count")!=null && p.getInt("presenter_count")!=null){
		int check = us.getInt("point_praise_count")/p.getInt("total_count")*p.getInt("presenter_count");
		setAttr("check", check);
		}
		setAttr("praise", p);
		setAttr("us", us);
		setAttr("openid", openid);
		setAttr("shop", shop);
		setAttr("shopid", shopId);
		setAttr("serverUrl", getServer());
		setAttr("message", message);
		render("/praise.jsp");
	}

	// 店面注册
	@ActionKey("/regrist")
	public void regrist() {
		String openid = getPara();
		setAttr("openid", openid);
		setAttr("serverUrl", getServer());
		render("/regrist.jsp");
	}

	// 兑换确认
	public void exchangeSure() {
		String shopId = getPara(0);
		String ruleid = getPara(1);
		String openid = getPara(2);
		Shop shop = Shop.dao.findById(shopId);
		ExchangeRule rule = ExchangeRule.dao.findById(ruleid);
		UserShop us = UserShop.dao.findFirst("select * from ka_user_shop where openid=? and shop_id=?",openid,shopId);
		setAttr("openid", openid);
		setAttr("us", us);
		setAttr("rule", rule);
		setAttr("shop", shop);
		setAttr("ruleid", ruleid);
		setAttr("shopid", shopId);
		setAttr("serverUrl", getServer());
		Log bl = Log.dao.findFirst("select * from log where openid=? and shop_id=? and checkorno=? and rule_id=?",openid,shopId,"no",ruleid);
		if(bl==null){
			render("/exchangeSure.jsp");
		}else{
			Date d = new Date();
			long day = 0;
			long hour = 0;
			long min = 0; 
			long sec = 0; 
			long diff ;
			long time1 = d.getTime(); 
			long time2 = bl.getTimestamp("valid_date").getTime(); 
			if(time1<time2){
				diff = time2 - time1;
				day = diff / (24 * 60 * 60 * 1000);
				hour = (diff / (60 * 60 * 1000) - day * 24); 
				min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
				sec = (diff/1000-day*24*60*60-hour*60*60-min*60); 
				if(day==2){
					day=3;
				}else if(day==1){
					day=2;
				}
				setAttr("day", day);
				setAttr("hour", hour);
				setAttr("min", min);
				setAttr("sec", sec);
				setAttr("logid", bl.getStr("id"));
				setAttr("code", openid+"_"+ruleid+"_"+shopId);
				render("/exchangeCode.jsp");
			}else{
				Log.dao.deleteById(bl.getStr("id"));
				render("/exchangeSure.jsp");
			}
		}
		
	}

	// 兑换码
	public void exchangeCode()throws Exception {
		String shopId = getPara(0);
		String ruleid = getPara(1);
		String openid = getPara(2);
		Shop shop = Shop.dao.findById(shopId);
		ExchangeRule rule = ExchangeRule.dao.findById(ruleid);
		UserShop us = UserShop.dao.findFirst("select * from ka_user_shop where openid=? and shop_id=?",openid,shopId);
		String content = rule.getInt("point_count")+"个卡点兑换"+rule.getStr("exchange_content");
		setAttr("us", us);
		setAttr("openid", openid);
		setAttr("rule", rule);
		setAttr("ruleid", ruleid);
		setAttr("shop", shop);
		setAttr("shopid", shopId);
		setAttr("serverUrl", getServer());
		if(us==null || us.getInt("use_point")==null){
			render("/nocard.jsp");
		}else if(rule.getInt("point_count")<=us.getInt("use_point"))
		{
			Log bl = Log.dao.findFirst("select * from log where openid=? and shop_id=? and checkorno=? and rule_id=?",openid,shopId,"no",ruleid);
			if(bl!=null){
				Date d = new Date();
				if(d.getTime()<bl.getTimestamp("create_date").getTime() + 3 * 24 * 60 * 60 * 1000){
					setAttr("day", "3");
					setAttr("logid", bl.getStr("id"));
					setAttr("code", openid+"_"+ruleid+"_"+shopId);
					render("/exchangeCode.jsp");
				}else{
					render("/exchangeSure.jsp");
				}				
			}else{
			Date d = new Date();
			Log l = new Log();
			l.set("id", System.currentTimeMillis() + "").set("valid_date", new Date(d.getTime() + 3 * 24 * 60 * 60 * 1000)).set("create_date", new Date()).set("content", content).set("openid", openid).set("shop_id", shopId).set("checkorno", "no").set("rule_id", ruleid).set("del_flag", "0").save();
			setAttr("logid", l.getStr("id"));
			Order order = Order.dao.findFirst("select * from ka_order where openid=? and shop_id=?",openid,shopId);
			if(order!=null){
				order.set("time", new Date()).update();
				}										
			//生成兑换的二维码
			bulidExchangeCode(openid+"_"+ruleid+"_"+shopId, "?nickName="+openid+"&&ruleId="+ruleid+"&&shopId="+shopId);
			setAttr("code", openid+"_"+ruleid+"_"+shopId);
			setAttr("day", "3");
			render("/exchangeCode.jsp");
			}
		}else{
			render("/nocard.jsp");
		}
	}
	
	// 兑换撤销
	public void exchangeSureCancel() {
		String openid=getPara(0);
		String shopId=getPara(1);
		String logid = getPara(2);
		Shop shop = Shop.dao.findById(shopId);
		Praise p = Praise.dao.findFirst("select * from ka_pointpraise_set where shop_id=? and type=?",shopId,"点赞");
		Praise s = Praise.dao.findFirst("select * from ka_pointpraise_set where shop_id=? and type=?",shopId,"分享");
		List<ExchangeRule> rules = ExchangeRule.dao.find("select * from ka_exchange_rule where shop_id=?",shopId);
		UserShop us = UserShop.dao.findFirst("select * from ka_user_shop where openid=? and shop_id=?",openid,shopId);
		ShopImage si = ShopImage.dao.findFirst("select * from ka_shop_image where shop_id=? and flag=?",shopId,"shop_img");
		List<ShopImage> sis = ShopImage.dao.find("select * from ka_shop_image where shop_id=? and flag=? order by create_date desc",shopId,"set");
		Log l = Log.dao.findFirst("select * from log where id=? and openid=? and shop_id=? and checkorno=?",logid,openid,shopId,"no");
		if(l==null){
			setAttr("message", "您已兑换成功，无法撤销！");
		}else{
			setAttr("message", "撤销成功");
			l.set("checkorno", "back").update();
		}
		setAttr("shopImages", sis);
		setAttr("shopImage", si);
		setAttr("share", s);
		setAttr("praise", p);
		setAttr("us", us);
		setAttr("rules", rules);
		setAttr("shop", shop);
		setAttr("openid", openid);
		setAttr("shopid", shopId);
		setAttr("serverUrl", getServer());
		forwardAction("/shopIndex/"+shopId+"-"+openid);
	}
	
	// 足迹详情
	public void footPrint() throws ParseException {
		List<footPrintVo> footPrintVos = new ArrayList<footPrintVo>();
		String shopId = getPara(0);
		String openid = getPara(1);
		String track = getPara(2);
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date d = new Date();
		Praise p = Praise.dao.findFirst("select * from ka_pointpraise_set where shop_id=? and type=?",shopId,"点赞");
		Praise s = Praise.dao.findFirst("select * from ka_pointpraise_set where shop_id=? and type=?",shopId,"分享");
		UserShop us = UserShop.dao.findFirst("select * from ka_user_shop where openid=? and shop_id=?",openid,shopId);
		Shop shop = Shop.dao.findById(shopId);
		List<Log> logs = Log.dao.find("select * from log where openid =? and shop_id=? and checkorno=? order by create_date desc",openid,shopId,"yes");
		List<ExchangeRecord> exs = ExchangeRecord.dao.find("select * from ka_exchange_record where nick_name=? and shop_id=? order by create_date desc",openid,shopId);
		List<Track> ts = Track.dao.find("select * from ka_track where nick_name=? and shop_id=? order by create_date desc",openid,shopId);//and valid_date >= '"+format.format(new Date())+"' 
		BigDecimal twenty = Track.dao.findFirst("select sum(t.usable_count) as track from ka_track t where t.shop_id = '"+shopId+"' and t.nick_name = '"+openid+"' and t.valid_date >= '"+format.format(new Date())+"' and t.valid_date <= '"+format.format(new Date(d.getTime() + 20 * 24 * 60 * 60 * 1000))+"' and t.state = '0'").getBigDecimal("track");
		Track daoqi = Track.dao.findFirst("select * from ka_track where nick_name=? and shop_id=? and valid_date >= '"+format.format(new Date())+"' and state = '0' order by valid_date asc limit 0,1",openid,shopId);	
		for(Track track2 : ts){
			footPrintVo printVo = new footPrintVo();
			printVo.setCreate_date(track2.getTimestamp("create_date"));
			printVo.setRemarks(track2.getStr("remarks"));
			printVo.setCount(track2.getInt("count"));
			footPrintVos.add(printVo);
		}
		for(ExchangeRecord record : exs){
			footPrintVo printVo = new footPrintVo();
			printVo.setCreate_date(record.getTimestamp("create_date"));
			printVo.setExchange_content(record.getStr("exchange_content"));
			printVo.setExchange_point(record.getStr("exchange_point"));
			footPrintVos.add(printVo);
		}
//		CompareUtils cm = new CompareUtils() {			
//		};
		
		Collections.sort(footPrintVos,this.GOODS_BY_INDATE);
		List<footPrintVo> footPrintVos2 = new ArrayList<footPrintVo>();
		for(int i=footPrintVos.size()-1;i>=0;i--){
			footPrintVo vo = footPrintVos.get(i);
			footPrintVos2.add(vo);
		}
		setAttr("list", footPrintVos2);
		setAttr("daoqi", daoqi);
		setAttr("twenty", twenty);
		setAttr("size", exs.size()+ts.size());
//		setAttr("exs", exs);
//		setAttr("ts", ts);
		setAttr("logs", logs);
		setAttr("openid", openid);
		setAttr("shop", shop);
		setAttr("shopid", shopId);
		setAttr("us", us);
		setAttr("track", track);
		setAttr("serverUrl", getServer());
		setAttr("share", s);
		setAttr("praise", p);		
		render("/footPrintView.jsp");
	}
	//用于列表按时间排序
	final Comparator<footPrintVo> GOODS_BY_INDATE = new Comparator<footPrintVo>(){          
        public int compare(footPrintVo o1, footPrintVo o2) {  
            try{                                          
//                SimpleDateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.ENGLISH);
                Date d1 = o1.getCreate_date();                         
                Date d2 = o2.getCreate_date();                
                return  d1.compareTo(d2);                         
            }catch(Exception e){
                e.printStackTrace();
            }         
            return -1;                        
        }  
    }; 	

	//店面首页
	@ActionKey("/shopIndex")
	public void shopIndex() {
		String shopId = getPara(0);		
		String openid = getPara(1);
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		BigDecimal track = Track.dao.findFirst("select sum(t.usable_count) as track from ka_track t where t.shop_id = '"+shopId+"' and t.nick_name = '"+openid+"' and t.valid_date >= '"+format.format(new Date())+"' and t.state = '0'").getBigDecimal("track");
	    BigDecimal count = Track.dao.findFirst("select sum(t.count) as count from ka_track t where t.shop_id = '"+shopId+"' and t.nick_name = '"+openid+"' ").getBigDecimal("count");
		Shop shop = Shop.dao.findById(shopId);
		Praise p = Praise.dao.findFirst("select * from ka_pointpraise_set where shop_id=? and type=?",shopId,"点赞");
		Praise s = Praise.dao.findFirst("select * from ka_pointpraise_set where shop_id=? and type=?",shopId,"分享");
		List<ExchangeRule> rules = ExchangeRule.dao.find("select * from ka_exchange_rule where shop_id=?",shopId);
		UserShop us = UserShop.dao.findFirst("select * from ka_user_shop where openid=? and shop_id=?",openid,shopId);
		String zox= "";
		if(us==null){
			UserShop us1 = new UserShop();
			if(track!=null){
			us1.set("id", System.currentTimeMillis() + "").set("openid", openid).set("shop_id", shopId).set("del_flag", "0").set("use_point",track).set("count_point", count).set("check_time", new Date()).set("check_time1", new Date()).save();
			}else{
				us1.set("id", System.currentTimeMillis() + "").set("openid", openid).set("shop_id", shopId).set("del_flag", "0").set("use_point",BigDecimal.valueOf(0)).set("count_point", BigDecimal.valueOf(0)).set("check_time", new Date()).set("check_time1", new Date()).save();	
			}
			setAttr("us", us1);
			Order o = new Order();
			ExchangeRule rule = ExchangeRule.dao.findFirst("select * from ka_exchange_rule where shop_id=? ORDER BY create_date desc LIMIT 0,1",shopId);
			if(rule!=null){
			o.set("id",  System.currentTimeMillis() + "").set("openid", openid).set("shop_id", shopId).set("time", rule.getTimestamp("create_date")).save();
			}else{
				o.set("id",  System.currentTimeMillis() + "").set("openid", openid).set("shop_id", shopId).save();	
			}
		}else{
			if(track!=null){
			us.set("use_point",track).set("count_point", count).update();
			}else{
				us.set("use_point",BigDecimal.valueOf(0)).set("count_point", BigDecimal.valueOf(0)).update();
			}
			if(us.getTimestamp("check_time")!=null){
				  int use_point = us.getBigDecimal("use_point").intValue();
				  int count_point = us.getBigDecimal("count_point").intValue();
				  SimpleDateFormat format1 = new SimpleDateFormat("d"); 
				  Date d = new Date();
				  String date = format1.format(d);		
				  String date1 = format1.format(us.getTimestamp("check_time"));	
				  if(!date.equals(date1)){
					  if(p!=null && p.getInt("total_count")!=null && us.getInt("point_praise_count")!=null){
					  
							int praise_count=us.getInt("point_praise_count");
							int total_count1= p.getInt("total_count");
							if(praise_count/total_count1>=1){
								us.set("use_point", use_point+praise_count/total_count1 * p.getInt("presenter_count")).set("count_point", count_point+praise_count/total_count1 * p.getInt("presenter_count")).update();
						        Calendar cal = Calendar.getInstance();
						        cal.setTime(d);
						        cal.add(Calendar.MONTH, Integer.parseInt(shop.getStr("valid_date")));
								Track track1 = new Track();
								DateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
//								DateFormat format3 = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
								track1.set("id", System.currentTimeMillis() + "").set("nick_name", openid).set("create_date", us.getTimestamp("check_time")).set("del_flag", "0").set("update_date", new Date()).set("create_date_str", format2.format(new Date())).set("state", "0").set("count", praise_count/total_count1 * p.getInt("presenter_count")).set("usable_count", praise_count/total_count1 * p.getInt("presenter_count")).set("shop_id", shopId).set("valid_date", cal.getTime()).set("remarks", "系统自动认领卡点").set("create_name", "我自己").save();
								Order order = Order.dao.findFirst("select * from ka_order where openid=? and shop_id=?",openid,shopId);
								if(order!=null){
									order.set("time", new Date()).update();
									}							
							  us.set("point_praise_count", us.getInt("point_praise_count")-praise_count/total_count1 * total_count1).set("operate", new Date()).update();
							  zox="先赞";							
							}
						  us.set("check_time", new Date()).update();
					  }
				  }
			}
			if(us.getTimestamp("check_time1")!=null){
				  SimpleDateFormat format1 = new SimpleDateFormat("d"); 
				  Date d = new Date();
				  String date = format1.format(d);		
				  String date1 = format1.format(us.getTimestamp("check_time1"));	
				  if(!date.equals(date1)){
					  if(s!=null && s.getInt("total_count")!=null && us.getInt("share_count")!=null){
							int share_count=us.getInt("share_count");
							int total_count1= s.getInt("total_count");
							if(share_count/total_count1>=1){
								  if(zox.equals("先赞")){
									  us.set("use_point", us.getInt("use_point")+share_count/total_count1 * s.getInt("presenter_count")).set("count_point", us.getInt("count_point")+share_count/total_count1 * s.getInt("presenter_count")).update();
									  }else{
										  us.set("use_point", us.getBigDecimal("use_point").intValue()+share_count/total_count1 * s.getInt("presenter_count")).set("count_point", us.getBigDecimal("count_point").intValue()+share_count/total_count1 * s.getInt("presenter_count")).update();	  
									  }
							        Calendar cal = Calendar.getInstance();
							        cal.setTime(d);
							        cal.add(Calendar.MONTH, Integer.parseInt(shop.getStr("valid_date")));
									Track track1 = new Track();
									DateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
//									DateFormat format3 = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
									track1.set("id", System.currentTimeMillis() + "").set("nick_name", openid).set("create_date", us.getTimestamp("check_time1")).set("del_flag", "0").set("update_date", new Date()).set("create_date_str", format2.format(new Date())).set("state", "0").set("count", share_count/total_count1 * s.getInt("presenter_count")).set("usable_count", share_count/total_count1 * s.getInt("presenter_count")).set("shop_id", shopId).set("valid_date", cal.getTime()).set("remarks", "系统自动认领卡点").set("create_name", "我自己").save();
									Order order = Order.dao.findFirst("select * from ka_order where openid=? and shop_id=?",openid,shopId);
									if(order!=null){
										order.set("time", new Date()).update();
										}													  
								  us.set("share_count", us.getInt("share_count")-share_count/total_count1 * total_count1).set("operate", new Date()).update();							
							}
							us.set("check_time1", new Date()).update();	
					  }
				  }				
			}
			Order order = Order.dao.findFirst("select * from ka_order where openid=? and shop_id=?",openid,shopId);
			if(order==null){
				Order o = new Order();
				ExchangeRule rule = ExchangeRule.dao.findFirst("select * from ka_exchange_rule where shop_id=? ORDER BY create_date desc LIMIT 0,1",shopId);
				if(rule!=null){
				o.set("id",  System.currentTimeMillis() + "").set("openid", openid).set("shop_id", shopId).set("time", rule.getTimestamp("create_date")).save();
				}else{
					o.set("id",  System.currentTimeMillis() + "").set("openid", openid).set("shop_id", shopId).set("time", new Date()).save();	
				}			
			}
		}
		ShopImage si = ShopImage.dao.findFirst("select * from ka_shop_image where shop_id=? and flag=?",shopId,"shop_img");
		List<ShopImage> sis = ShopImage.dao.find("select * from ka_shop_image where shop_id=? and flag=? order by create_date desc",shopId,"set");
		if(sis!=null && rules!=null){
		for(int i = 0;i<sis.size();i++){
			if(rules.size()>=i+1){
			rules.get(i).set("file_name", sis.get(i).getStr("file_name")).update();
			}
		}
		}
		Log log = Log.dao.findFirst("select * from log where openid =? and shop_id=? and checkorno=? and create_date=(select max(create_date) from log)",openid,shopId,"yes");
		Track track1 = Track.dao.findFirst("select * from ka_track where shop_id=? and nick_name=? order by create_date desc LIMIT 0,1 ",shopId,openid);
		ExchangeRecord exchangeRecord = ExchangeRecord.dao.findFirst("select * from ka_exchange_record where shop_id=? and nick_name=? order by create_date desc LIMIT 0,1",shopId,openid);
		if(track1==null && exchangeRecord==null){
			
		}else if(track1!=null && exchangeRecord!=null){
			if(track1.getTimestamp("create_date").getTime()>exchangeRecord.getTimestamp("create_date").getTime()){
				setAttr("date", track1.getTimestamp("create_date"));
				if(track1.getStr("remarks")!=null && track1.getStr("remarks").indexOf("点赞")!=-1){
					setAttr("praise1", track1.getStr("remarks"));
				}
				if(track1.getStr("remarks")!=null && track1.getStr("remarks").indexOf("分享")!=-1){
					setAttr("share1", track1.getStr("remarks"));
				}
				if(track1.getStr("remarks")!=null && track1.getStr("remarks").equals("系统自动认领卡点")){
					setAttr("system", track1.getStr("remarks"));
				}
				if(track1.getStr("remarks")!=null && track1.getStr("remarks").indexOf("提供")!=-1){
					setAttr("advice", track1.getStr("remarks"));
				}
				if(track1.getStr("remarks")!=null && track1.getStr("remarks").indexOf("关注")!=-1){
					setAttr("guanzhu", track1.getStr("remarks"));
				}
				if(track1.getStr("remarks")!=null && track1.getStr("remarks").indexOf("签到")!=-1){
					setAttr("qiandao", track1.getStr("remarks"));
				}				
				setAttr("content", track1.getInt("count"));
			}else{
				setAttr("date", exchangeRecord.getTimestamp("create_date"));
				setAttr("point", exchangeRecord.getStr("exchange_point"));
				setAttr("econtent", exchangeRecord.getStr("exchange_content"));
			}
		}else if(track1!=null && exchangeRecord==null){
			setAttr("date", track1.getTimestamp("create_date"));
			if(track1.getStr("remarks")!=null && track1.getStr("remarks").indexOf("点赞")!=-1){
				setAttr("praise1", track1.getStr("remarks"));
			}
			if(track1.getStr("remarks")!=null && track1.getStr("remarks").indexOf("分享")!=-1){
				setAttr("share1", track1.getStr("remarks"));
			}
			if(track1.getStr("remarks")!=null && track1.getStr("remarks").equals("系统自动认领卡点")){
				setAttr("system", track1.getStr("remarks"));
			}
			if(track1.getStr("remarks")!=null && track1.getStr("remarks").indexOf("提供")!=-1){
				setAttr("advice", track1.getStr("remarks"));
			}			
			if(track1.getStr("remarks")!=null && track1.getStr("remarks").indexOf("关注")!=-1){
				setAttr("guanzhu", track1.getStr("remarks"));
			}
			if(track1.getStr("remarks")!=null && track1.getStr("remarks").indexOf("签到")!=-1){
				setAttr("qiandao", track1.getStr("remarks"));
			}				
			setAttr("content", track1.getInt("count"));			
		}else{
			setAttr("date", exchangeRecord.getTimestamp("create_date"));
			setAttr("point", exchangeRecord.getStr("exchange_point"));
			setAttr("econtent", exchangeRecord.getStr("exchange_content"));			
		}
		setAttr("log", log);
		setAttr("track", track);
		setAttr("shopImages", sis);
		setAttr("shopImage", si);
		setAttr("share", s);
		setAttr("praise", p);
		setAttr("us", us);
		setAttr("rules", rules);
		setAttr("shop", shop);
		setAttr("openid", openid);
		setAttr("shopid", shopId);
		setAttr("serverUrl", getServer());
		setSessionAttr("shopid", shopId);
		setSessionAttr("openid", openid);
		setSessionAttr("serverUrl", getServer());
		setSessionAttr("shopname", shop.getStr("shop_name"));
		setSessionAttr("shopimage", shop.getStr("head_image"));		
		
		render("/shopIndex.jsp");
	}
	//分享首页
	@ActionKey("/shopShare")
	public void shopShare() {
		String shopId = getPara(0);
		String openid = getPara(1);
		Shop shop = Shop.dao.findById(shopId);
		Praise p = Praise.dao.findFirst("select * from ka_pointpraise_set where shop_id=? and type=?",shopId,"点赞");
		Praise s = Praise.dao.findFirst("select * from ka_pointpraise_set where shop_id=? and type=?",shopId,"分享");
		List<ExchangeRule> rules = ExchangeRule.dao.find("select * from ka_exchange_rule where shop_id=?",shopId);
		UserShop us = UserShop.dao.findFirst("select * from ka_user_shop where openid=? and shop_id=?",openid,shopId);
		ShopImage si = ShopImage.dao.findFirst("select * from ka_shop_image where shop_id=? and flag=?",shopId,"shop_img");
		List<ShopImage> sis = ShopImage.dao.find("select * from ka_shop_image where shop_id=? and flag=? order by create_date desc",shopId,"set");
		Log log = Log.dao.findFirst("select * from log where openid =? and shop_id=? and checkorno=? and create_date=(select max(create_date) from log)",openid,shopId,"yes");
		setAttr("log", log);
		setAttr("shopImages", sis);
		setAttr("shopImage", si);
		setAttr("share", s);
		setAttr("praise", p);
		setAttr("us", us);
		setAttr("rules", rules);
		setAttr("shop", shop);
		setAttr("openid", openid);
		setAttr("shopid", shopId);
		setAttr("serverUrl", getServer());
		int day_count = 0;
		int daycount = 0;
		int day_share_count = 0;
		String total_count = "";
		int shareCount = 0;
		if(us!=null){
		if(us.getInt("share_count")!=null){
			shareCount=us.getInt("share_count");
		}
		}
		if(shop.getStr("total_count1")==null){
		total_count = "0";
		}else{
			total_count = shop.getStr("total_count1");
		}
		int praise = Integer.parseInt(total_count)+1;
		String praise1= Integer.toString(praise);		
		if(s==null)
		{
			day_count = 0;
		}else{
			day_count = s.getInt("day_count");
		}
		if(us!=null){
		if(us.getInt("day_share_count")!=null){
			day_share_count = us.getInt("day_share_count");
		}
		}
			daycount =day_count;
		
		  SimpleDateFormat format = new SimpleDateFormat("d"); 
		  Date d = new Date();
		  String date = format.format(d);	
		if(!s.getStr("enabled").equals("关闭")){  
		if(us==null){
			if(daycount==0){
			}else if(openid!=null){
			UserShop u = new UserShop();
			shop.set("total_count1", praise1).update();
			u.set("day_share_count", day_share_count+1).set("share_time", date).set("share_count", shareCount+1).set("id", System.currentTimeMillis() + "").set("openid", openid).set("shop_id", shopId).save();
			}else{
			}
		}else{
			if(us.getStr("share_time")!=null){
			if(us.getStr("share_time").equals(date)){
				if(day_share_count==daycount){
				}else{
				shop.set("total_count1", praise1).update();
				us.set("day_share_count", day_share_count+1).set("share_time", date).set("share_count", shareCount+1).update();				
					}
			}else{
				day_share_count=0;
				if(day_share_count==daycount){
				}else{
				shop.set("total_count1", praise1).update();
				us.set("day_share_count", day_share_count+1).set("share_time", date).set("share_count", shareCount+1).update();				
					}
			}
			}else{
				if(daycount==0){
				}else{
				shop.set("total_count1", praise1).update();
				us.set("day_share_count", day_share_count+1).set("share_time", date).set("share_count", shareCount+1).update();				
				}				
			}
		}
		}
		render("/shopShare.jsp");
	}

	//店面列表
	@ActionKey("/shopList")
	public void shopList() {
		try {
			DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String openid = getPara();
			StringBuffer whee = new StringBuffer();
			whee.append("select s.head_image,s.address,s.shop_name,s.id,s.total_count,");
			whee.append("(select sum(t.usable_count) from ka_track t where t.shop_id = s.id and t.nick_name = '"+openid+"' and t.valid_date >= '"+format.format(new Date())+"' and t.state = '0') as track,");
			whee.append("(SELECT r.exchange_content from ka_exchange_rule r where r.shop_id = s.id ORDER BY r.create_date desc LIMIT 0,1) as exchange_content,");
			whee.append("(SELECT p.point_count from ka_exchange_rule p where p.shop_id = s.id ORDER BY p.create_date desc LIMIT 0,1) as point_count,");
//			whee.append("(SELECT u.operate from ka_user_shop u where u.shop_id = s.id and u.openid = '"+openid+"') as operate,");
			whee.append("(SELECT o.time from ka_order o where o.shop_id = s.id and o.openid = '"+openid+"') as time");
//			whee.append("(SELECT d.update_date from ka_exchange_rule d where d.shop_id = s.id ORDER BY d.create_date desc LIMIT 0,1) as date,");
//			whee.append("(SELECT e.create_date from ka_exchange_record e where e.shop_id = s.id and e.nick_name = '"+openid+"' order by e.create_date LIMIT 0,1) as e_date");
	/*		List<Shop> shops = Shop.dao.find("select ka_shop.id,ka_shop.update_date,address,head_image,shop_name,total_count,ka_exchange_rule.point_count,operate,exchange_content,use_point from ka_shop left join ka_exchange_rule on ka_shop.id=ka_exchange_rule.shop_id left join ka_user_shop on ka_shop.id=ka_user_shop.shop_id where ka_user_shop.openid = ? GROUP BY shop_name ORDER BY ka_exchange_rule.create_date DESC,ka_user_shop.operate DESC","om8Hft4ORmYd7H227TKVNsbzmDjw");	
	*/		List<Object> param = new ArrayList<Object>();
			Page<Shop> pager = Shop.dao.paginate(
					getParaToInt("pager.pageNumber", 1),
					getParaToInt("pager.pageSize", 100),
					whee.toString(), 
					"from ka_shop s where s.parent_id is null and s.id in(SELECT l.shop_id from ka_order l where l.openid = '"+openid+"') ORDER BY time desc",
					param.toArray());
			setAttr("pager",pager);
			
			setAttr("openid", openid);
			/*setAttr("shops", shops);*/
			setAttr("serverUrl", getServer());
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		render("/shopList.jsp");
	}

	// 店面搜索
	@ActionKey("/searchList")
	public void searchList(){
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String openid =getPara("openid");
		String text = getPara("searchlist");
		if(text!=null){
			setSessionAttr("text", text);
		}else{
			text=getSessionAttr("text");
		}
		if(openid!=null){
			setSessionAttr("openid", openid);
		}else{
			openid=getSessionAttr("openid");
		}
//		String shopid = "";
		if(text==null){
			text="";
		}
		if(openid==null){
		openid=getPara();
		}
//		Shop shop = Shop.dao.findFirst("select * from ka_shop where shop_name like ?","%"+text+"%");
//		if(shop!=null){
//			shopid=shop.getStr("id");
//		}
		Track track = Track.dao.findFirst("select * from ka_track where nick_name=?",openid);
		Order order = Order.dao.findFirst("select * from ka_order where openid=?",openid);
//		if(text.isEmpty() || text.trim().equals("")){}else{
		StringBuffer whee = new StringBuffer();
		whee.append("select s.head_image,s.address,s.shop_name,s.id,s.total_count,s.update_date,");
		if(track!=null){
		whee.append("(select sum(t.usable_count) from ka_track t where t.shop_id = s.id and t.nick_name = '"+openid+"' and t.valid_date >= '"+format.format(new Date())+"' and t.state = '0') as track,");
		}
		
		whee.append("(SELECT r.exchange_content from ka_exchange_rule r where r.shop_id = s.id ORDER BY r.create_date desc LIMIT 0,1) as exchange_content,");
		
		if(order!=null){
		whee.append("(SELECT o.time from ka_order o where o.shop_id = s.id and o.openid = '"+openid+"') as time,");
		}
		
		whee.append("(SELECT p.point_count from ka_exchange_rule p where p.shop_id = s.id ORDER BY p.create_date desc LIMIT 0,1) as point_count");
//		whee.append("(SELECT u.operate from ka_user_shop u where u.shop_id = s.id and u.openid = '"+openid+"') as operate,");
//		whee.append("(SELECT d.update_date from ka_exchange_rule d where d.shop_id = s.id ORDER BY d.create_date desc LIMIT 0,1) as date,");
//		whee.append("(SELECT e.create_date from ka_exchange_record e where e.shop_id = s.id and e.nick_name = '"+openid+"' order by e.create_date LIMIT 0,1) as e_date");
		List<Object> param = new ArrayList<Object>();
		if(order!=null){
		Page<Shop> pager = Shop.dao.paginate(
				getParaToInt("pager.pageNumber", 1),
				getParaToInt("pager.pageSize", 100),
				whee.toString(), 
				"from ka_shop s where s.shop_name like '%"+text.trim()+"%' and s.parent_id is null ORDER BY time desc",
				param.toArray());
		setAttr("pager",pager);
		}else{
			Page<Shop> pager = Shop.dao.paginate(
					getParaToInt("pager.pageNumber", 1),
					getParaToInt("pager.pageSize", 100),
					whee.toString(), 
					"from ka_shop s where s.shop_name like '%"+text.trim()+"%' and s.parent_id is null order by s.update_date desc",
					param.toArray());
			setAttr("pager",pager);			
		}
//		}
		/*List<Shop> shops = Shop.dao.find("select ka_shop.id,ka_shop.update_date,address,head_image,shop_name,total_count,ka_exchange_rule.point_count,operate,exchange_content,use_point from ka_shop left join ka_exchange_rule on ka_shop.id=ka_exchange_rule.shop_id left join ka_user_shop on ka_shop.id=ka_user_shop.shop_id where ka_shop.shop_name like ? and ka_user_shop.openid = ? GROUP BY shop_name ORDER BY ka_shop.update_date DESC","%"+text.trim()+"%",openid);*/
		setAttr("openid", openid);
		/*setAttr("shops", shops);*/
		setAttr("text", text);
		setAttr("serverUrl", getServer());
		render("/shopList.jsp");	
		
	}
	
	// 店面保存
	@ActionKey("/addShop")
	public void addShop() {
		String openid = getPara("openid");
		setAttr("openid", openid);
		String phone = getPara("phone");
		String password = getPara("password");
		String repassword = getPara("repassword");
		String shopName = getPara("shopName");
		String address = getPara("address");
		String pmessage = "";
		String passmessage = "";
		String repassmessage = "";
		String dmessage = "";
		String amessage = "";
		setAttr("phone", phone);
		setAttr("password", password);
		setAttr("repassword", repassword);
		setAttr("shopName", shopName);
		setAttr("address", address);
		
		Shop pshop = Shop.dao.findFirst("select * from ka_shop where login_name=?",phone);
		Shop sshop = Shop.dao.findFirst("select * from ka_shop where shop_name=?",shopName);
		Shop ashop = Shop.dao.findFirst("select * from ka_shop where address=?",address);
		if(phone==null||phone.trim().equals("")){
			pmessage="请输入用户名";
			setAttr("pmessage", pmessage);
			render("/regrist.jsp");
		}else if(!(phone.matches("^\\d{1,11}$"))){
			pmessage="请输入正确手机号";
			setAttr("pmessage", pmessage);
			render("/regrist.jsp");		
		}else if(pshop!=null){
			pmessage="用户名已存在";
			setAttr("pmessage", pmessage);
			render("/regrist.jsp");
		}else if(password==null||password.trim().equals("")){
			passmessage="请输入密码";
			setAttr("passmessage", passmessage);
			render("/regrist.jsp");			
		}else if(repassword==null||repassword.trim().equals("")){
			repassmessage="请重复输入密码";
			setAttr("repassmessage", repassmessage);
			render("/regrist.jsp");						
		}else if(!password.equals(repassword)){
			repassmessage="前后密码不一致";
			setAttr("repassmessage", repassmessage);
			render("/regrist.jsp");									
		}else if(shopName==null||shopName.trim().equals("")){
			dmessage="请输入店铺名";
			setAttr("dmessage", dmessage);
			render("/regrist.jsp");												
		}else if(sshop!=null){
			dmessage="店铺名已存在";
			setAttr("dmessage", dmessage);
			render("/regrist.jsp");															
		}else if(address==null||address.trim().equals("")){
			amessage="请输入地址";
			setAttr("amessage", amessage);
			render("/regrist.jsp");																		
		}else if(ashop!=null){
			amessage="地址已存在";
			setAttr("amessage", amessage);
			render("/regrist.jsp");																				
		}else{
		getModel(Shop.class).set("phone", phone)
				.set("valid_date", "6")
				.set("login_name", getPara("phone"))
				.set("password", password)
				.set("shop_name", shopName)
				.set("address", address)
				.set("id", System.currentTimeMillis() + "").set("del_flag", "0").save();
		/* shopIndex(); */
		setAttr("serverUrl", getServer());
		render("/registerSuccess.jsp");
		}
	}

	// 店面核实
	@ActionKey("/addCheck")
	public void addCheck() {
		String openid = getPara("openid");
		setAttr("openid", openid);
		String phone = getPara("phone");
		String password = getPara("password");//主营业务
		String shopName = getPara("shopName");
		String address = getPara("address");
		String pmessage = "";
		String passmessage = "";
		String dmessage = "";
		String amessage = "";
		setAttr("phone", phone);
		setAttr("password", password);
		setAttr("shopName", shopName);
		setAttr("address", address);
		
		Shop pshop = Shop.dao.findFirst("select * from ka_shop where phone=?",phone);
		Shop sshop = Shop.dao.findFirst("select * from ka_shop where shop_name=?",shopName);
		Shop ashop = Shop.dao.findFirst("select * from ka_shop where address=?",address);
		Check check_phone = Check.dao.findFirst("select * from ka_check where phone=?",phone);
		Check check_name = Check.dao.findFirst("select * from ka_check where shop_name=?",shopName);
		Check check_address = Check.dao.findFirst("select * from ka_check where address=?",address);
		if(shopName==null||shopName.trim().equals("")){
			dmessage="请输入店铺名";
			setAttr("dmessage", dmessage);
			render("/join.jsp");											
		}else if(sshop!=null || check_name!=null){
			dmessage="店铺名已存在";
			setAttr("dmessage", dmessage);
			render("/join.jsp");															
		}else if(password==null||password.trim().equals("")){
			passmessage="请输入主营业务";
			setAttr("passmessage", passmessage);
			render("/join.jsp");		
		}else if(address==null||address.trim().equals("")){
			amessage="请输入地址";
			setAttr("amessage", amessage);
			render("/join.jsp");																		
		}else if(ashop!=null || check_address!=null){
			amessage="地址已存在";
			setAttr("amessage", amessage);
			render("/join.jsp");																				
		}else if(phone==null||phone.trim().equals("")){
			pmessage="请输入手机号";
			setAttr("pmessage", pmessage);
			render("/join.jsp");
		}else if(!(phone.matches("^\\d{1,11}$"))){
			pmessage="请输入正确手机号";
			setAttr("pmessage", pmessage);
			render("/join.jsp");	
		}else if(pshop!=null || check_phone!=null){
			pmessage="该手机号已注册过，请更换手机号！";
			setAttr("pmessage", pmessage);
			render("/join.jsp");
		}else{
		getModel(Check.class).set("phone", phone)
				.set("password", password)
				.set("shop_name", shopName)
				.set("address", address)
				.set("id", System.currentTimeMillis() + "").set("del_flag", "0").set("create_date", new Date()).save();
		/* shopIndex(); */
		setAttr("serverUrl", getServer());
		render("/registerSuccess.jsp");
		}
	}

	// 二维码浏览
	@ActionKey("/code")
	public void code() {
		String openid = getPara(0);
		setAttr("openid", openid);
		System.out.println("OPENID=" + openid);
		setAttr("serverUrl", getServer());
		render("/code.jsp");
	}

	public void check() throws Exception {
		Boolean isGet = getRequest().getMethod().equals("GET");
		String timestamp = getPara("timestamp"); // 时间戳
		String nonce = getPara("nonce"); // 随机数
		// 处理微信验证
		if (isGet) {
			String signature = getPara("signature"); // 微信加密签名
			String echostr = getPara("echostr"); // 随机字符串
			// 确认请求来至微信
			if (WxUtils.checkSignature(signature, timestamp, nonce)) {
				try {
					this.getResponse().getWriter().print(echostr);
					renderNull();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			// 处理微信发送信息
		} else {
			try {
				getResponse().setCharacterEncoding("UTF-8");
				getResponse().setContentType("text/xml");

				OutMessage oms = new OutMessage();
				ServletInputStream in;
				in = getRequest().getInputStream();

				// 转换微信post过来的xml内容
				XStream xs = XStreamFactory.init(false);
				xs.alias("xml", InMessage.class);
				xs.alias("ScanCodeInfo", ScanCodeInfo.class);
				String xmlMsg = WxUtils.inputStream2String(in);

//				WXBizMsgCrypt pc = new WXBizMsgCrypt(WxUtils.TOKEN, WxUtils.ENCODINGAESKEY, WxUtils.APPID);
//				//如果采用安全模式，则需对信息进行解密
//				if("aes".equals(getPara("encrypt_type"))){
//					xmlMsg = pc.decryptMsg(getPara("msg_signature"), timestamp, nonce, xmlMsg);
//				}

				// logger.debug("输入消息:[" + xmlMsg + "]");

				InMessage msg = (InMessage) xs.fromXML(xmlMsg);
				// 获取自定消息处理器，如果自定义处理器则使用默认处理器。
				String handler = "cn.copera.kaka.wx.handler.MessageProcessingHandlerImpl";
				try {
					// 加载处理器
					Class<?> clazz = Class.forName(handler);
					MessageProcessingHandler processingHandler = (MessageProcessingHandler) clazz
							.newInstance();
					// 取得消息类型
					String type = msg.getMsgType();
					System.out.println("客户OpenID为" + msg.getFromUserName().replace("-", "a"));
					Method mt = clazz.getMethod(type + "TypeMsg",
							InMessage.class);
					oms = (OutMessage) mt.invoke(processingHandler, msg);
					if (oms == null) {
						oms = new TextOutMessage();
						((TextOutMessage) oms).setContent("系统错误!");
					}
					setMsgInfo(oms, msg);
				} catch (Exception e) {
					oms = new TextOutMessage();
					((TextOutMessage) oms).setContent("系统错误!");
					try {
						setMsgInfo(oms, msg);
					} catch (Exception e1) {
					}
				}
				/*
				 * ((TextOutMessage)
				 * oms).setContent("您发送信息类型是"+msg.getMsgType()+
				 * ",您在此的OpenID为"+msg
				 * .getFromUserName()+"<br>事件类型为"+msg.getEvent(
				 * )+"事件KEY值为"+msg.getEventKey()); // 把发送对象转换为xml输出 xs =
				 * XStreamFactory.init(true); xs.alias("xml", oms.getClass());
				 * String xml = xs.toXML(oms);
				 */
				String xml = "";
				if ("event".equals(msg.getMsgType())
						&& "CLICK".equals(msg.getEvent())) {
					
					if ("CODE".equals(msg.getEventKey())) { // 我的二维码
						bulid(msg.getFromUserName().replace("-", "a"),msg.getFromUserName().replace("-", "a"));
	                    //大的二维码
						bulidCode(msg.getFromUserName().replace("-", "a")+"big",msg.getFromUserName().replace("-", "a"));
						// 保留关注者信息
						List<User> cs = User.dao.find(
								"SELECT * FROM ka_user WHERE nick_name=?",
								msg.getFromUserName().replace("-", "a"));
						System.out.println("当前个数:" + cs.size());
						if (cs == null || cs.size() == 0) {
							getModel(User.class).set("create_date", new Date())
									.set("nick_name", msg.getFromUserName().replace("-", "a"))
									.set("id", msg.getFromUserName().replace("-", "a")).set("del_flag", "0").save();
						}					
						xml = WxUtils.getTwoCode(msg, msg.getFromUserName().replace("-", "a")
								+ ".jpg");					
					} else if ("foot".equals(msg.getEventKey())) { // 我的足迹
						xml = WxUtils.getNewFoot(msg);
					}else if("allshop".equals(msg.getEventKey())){
						xml = WxUtils.getAllShop(msg);
					}else if("connect".equals(msg.getEventKey())){
						xml = WxUtils.getConnect(msg);
					}
				} else if ("event".equals(msg.getMsgType())
						&& "subscribe".equals(msg.getEvent())) {

					bulid(msg.getFromUserName().replace("-", "a"),msg.getFromUserName().replace("-", "a"));
                    //大的二维码
					bulidCode(msg.getFromUserName().replace("-", "a")+"big",msg.getFromUserName().replace("-", "a"));
					xml = WxUtils.getWelcomeContent(msg, msg.getFromUserName().replace("-", "a")
							+ ".jpg"); // 被关注时的显示信息
					// 保留关注者信息
					List<User> cs = User.dao.find(
							"SELECT * FROM ka_user WHERE nick_name=?",
							msg.getFromUserName().replace("-", "a"));
					System.out.println("当前个数:" + cs.size());
					if (cs == null || cs.size() == 0) {
						getModel(User.class).set("create_date", new Date())
								.set("nick_name", msg.getFromUserName().replace("-", "a"))
								.set("id", msg.getFromUserName().replace("-", "a")).set("del_flag", "0").save();
					}
					
				}else if ("event".equals(msg.getMsgType())
						&& "scancode_waitmsg".equals(msg.getEvent())) {
					String shopId = null;
					if(xmlMsg.indexOf("ScanResult")!=-1){
						int start = xmlMsg.indexOf("<ScanResult><![CDATA[");
						int end = xmlMsg.indexOf("]]></ScanResult>");
						shopId = xmlMsg.substring(start+21, end);
						
					}
					Shop shop = Shop.dao.findById(shopId);
					if(shop!=null){
					String shopName = shop.get("shop_name");
					ShopImage si = ShopImage.dao.findFirst("select * from ka_shop_image where shop_id=? and flag=?",shopId,"shop_img");
					String shopImage =null;
					if(si!=null){
					shopImage = si.getStr("file_name");
					}
					xml = WxUtils.getShopScanContent(msg, shopName, shopId,getServer()+shopImage);					
					
					}else{
						((TextOutMessage) oms)
						.setContent("您扫描的二维码不是系统店铺二维码，请重新选择二维码进行扫描！");
						xs = XStreamFactory.init(true);
						xs.alias("xml", oms.getClass());
						xml = xs.toXML(oms);
					}
				}else if("text".equals(msg.getMsgType())){
					xml = WxUtils.getSmartWord(msg,(TextOutMessage) oms);	//传送消息类型为文本信息
					
				}  else {
					((TextOutMessage) oms)
							.setContent("感谢您的关注，平台功能请查看菜单中的如何使用。");
					xs = XStreamFactory.init(true);
					xs.alias("xml", oms.getClass());
					xml = xs.toXML(oms);
				}
				//如果采用安全模式，则需对信息进行加密
//				if("aes".equals(getPara("encrypt_type"))){
//					xml = pc.encryptMsg(xml, timestamp, nonce);
//				}

				getResponse().getWriter().write(xml);
				renderNull();
			} catch (IOException e) {
			}
		}
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public void bulid(String filename,String content) throws Exception {
		// 生成二维码图片
		//String text = "二维码内容，可以是链接也可以是文本";
		int width = 320;
		int height = 200;
		Hashtable hints = new Hashtable();
		hints.put(EncodeHintType.CHARACTER_SET, "utf-8");// 内容所使用编码
		BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
				BarcodeFormat.QR_CODE, width, height, hints);
		String path = "/images/";
		String realPath = getRequest().getSession().getServletContext()
				.getRealPath(path);
		String imgPath = realPath + "/" + filename + ".jpg";
		File f = new File(imgPath);
		if(f.exists()){
			f.delete();
		}
		File outputFile = new File(imgPath);
		// File.separator
		String format = "jpg";// 二维码的图片格式
		MatrixToImageWriter.writeToFile(bitMatrix, format, outputFile);
		//加入LOGO
		String logoPath = getRequest().getSession().getServletContext()
				.getRealPath("/images/kaka.png");
		 BarcodeFactory  
         .encode(content+"kaka",  
                 320, 200, logoPath, imgPath); 
	}
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public void bulidCode(String filename,String content) throws Exception {
		// 生成二维码图片
		//String text = "二维码内容，可以是链接也可以是文本";
		int width = 400;
		int height = 400;
		Hashtable hints = new Hashtable();
		hints.put(EncodeHintType.CHARACTER_SET, "utf-8");// 内容所使用编码
		BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
				BarcodeFormat.QR_CODE, width, height, hints);
		String path = "/images/";
		String realPath = getRequest().getSession().getServletContext()
				.getRealPath(path);
		String imgPath = realPath + "/" + filename + ".jpg";
		File outputFile = new File(imgPath);
		// File.separator
		String format = "jpg";// 二维码的图片格式
		MatrixToImageWriter.writeToFile(bitMatrix, format, outputFile);
		//加入LOGO
		String logoPath = getRequest().getSession().getServletContext()
				.getRealPath("/images/kaka.png");
		 BarcodeFactory  
         .encode(content+"kaka",  
                 400, 400, logoPath, imgPath); 
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public void bulidMyCode(String filename,String content) throws Exception {
		// 生成二维码图片
		//String text = "二维码内容，可以是链接也可以是文本";
		int width = 400;
		int height = 400;
		Hashtable hints = new Hashtable();
		hints.put(EncodeHintType.CHARACTER_SET, "utf-8");// 内容所使用编码
		BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
				BarcodeFormat.QR_CODE, width, height, hints);
		String path = "/images/";
		String realPath = getRequest().getSession().getServletContext()
				.getRealPath(path);
		String imgPath = realPath + "/" + filename + ".jpg";
		File outputFile = new File(imgPath);
		// File.separator
		String format = "jpg";// 二维码的图片格式
		MatrixToImageWriter.writeToFile(bitMatrix, format, outputFile);
		//加入LOGO
		String logoPath = WxUtils.getWxUserInfoPic(content, WxUtils.getAccessToken("wx25d8154f7a1cd8a7", "c8184573e16c4716a78ed2349cd00270"));
		System.out.println(logoPath);
		//		String logoPath = getRequest().getSession().getServletContext()
//				.getRealPath("/images/kaka.png");
		 BarcodeFactory  
         .encode(content+"kaka",  
                 400, 400, logoPath, imgPath); 
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public void bulidExchangeCode(String filename,String content) throws Exception {
		// 生成二维码图片
		//String text = "二维码内容，可以是链接也可以是文本";
		int width = 400;
		int height = 400;
		Hashtable hints = new Hashtable();
		hints.put(EncodeHintType.CHARACTER_SET, "utf-8");// 内容所使用编码
		BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
				BarcodeFormat.QR_CODE, width, height, hints);
		String path = "/images/";
		String realPath = getRequest().getSession().getServletContext()
				.getRealPath(path);
		String imgPath = realPath + "/" + filename + ".jpg";
		File outputFile = new File(imgPath);
		// File.separator
		String format = "jpg";// 二维码的图片格式
		MatrixToImageWriter.writeToFile(bitMatrix, format, outputFile);
		//加入LOGO
		String logoPath = getRequest().getSession().getServletContext()
				.getRealPath("/images/kaka.png");
		 BarcodeFactory  
         .encode(content,  
                 400, 400, logoPath, imgPath); 
	}
	private void setMsgInfo(OutMessage oms, InMessage msg) throws Exception {
		// 设置发送信息
		Class<?> outMsg = oms.getClass().getSuperclass();
		Field CreateTime = outMsg.getDeclaredField("CreateTime");
		Field ToUserName = outMsg.getDeclaredField("ToUserName");
		Field FromUserName = outMsg.getDeclaredField("FromUserName");

		ToUserName.setAccessible(true);
		CreateTime.setAccessible(true);
		FromUserName.setAccessible(true);

		CreateTime.set(oms, new Date().getTime());
		ToUserName.set(oms, msg.getFromUserName().replace("-", "a"));
		FromUserName.set(oms, msg.getToUserName());
	}

	public void hello() {
		Boolean isGet = getRequest().getMethod().equals("GET");
		if (isGet) {
			String para = getPara("word");
			System.out.println("Welcome GET " + para);
		} else {
			String para = getPara("word");
			System.out.println("Welcome POST " + para);
		}
	}
	/**
	 * 注册用户名确认
	 */	
	public void phoneCheck(){
		String phone = getPara("phone");
		Shop shop = Shop.dao.findFirst("select * from ka_shop where phone=?",phone);
		Check check = Check.dao.findFirst("select * from ka_check where phone=?",phone);
		if(shop==null && check==null){
			if(phone==null||phone.trim().equals("")){
				String message = "手机号不能为空！";
				renderJson("message",message);									
			}else if(!(phone.matches("^\\d{1,11}$"))){
				String message = "请输入正确手机号";
				renderJson("message",message);												
			}else{
			String message = "手机号可用";
			renderJson("message",message);		
			}
		}else{
			String message = "手机号已存在";
			renderJson("message",message);					
		}
	}
	/**
	 * 密码确认
	 */	
	public void passwordCheck(){
		String password = getPara("password");
		if(password==null||password.trim().equals("")){
			String message = "请输入主营业务";
			renderJson("message",message);											
		}else{
			String message = "主营业务可用";
			renderJson("message",message);								
		}
	}
	/**
	 * 重复密码确认
	 */	
	public void repasswordCheck(){
		String password = getPara("password");
		String repassword = getPara("repassword");
		if(repassword==null||repassword.trim().equals("")){
			String message = "请重复输入密码";
			renderJson("message",message);														
		}else if(password.equals(repassword)){
			String message = "ok";
			renderJson("message",message);																	
		}else{
			String message = "密码不一致";
			renderJson("message",message);																				
		}
	}
	/**
	 * 店名确认
	 */	
	public void shopNameCheck(){
		String shopName = getPara("shopName");
		Shop shop = Shop.dao.findFirst("select * from ka_shop where shop_name=?",shopName);
		Check check = Check.dao.findFirst("select * from ka_check where shop_name=?",shopName);
		if(shop==null && check==null){
			if(shopName==null||shopName.trim().equals("")){
				String message = "请输入店名";
				renderJson("message",message);									
			}else{
			String message = "店名可用";
			renderJson("message",message);		
			}
		}else{
			String message = "店铺名已存在";
			renderJson("message",message);								
		}
	}
	
	/**
	 * 地址确认
	 */	
	public void addressCheck(){
		String address = getPara("address");
		Shop shop = Shop.dao.findFirst("select * from ka_shop where address=?",address);
		Check check = Check.dao.findFirst("select * from ka_check where address=?",address);
		if(shop==null && check==null){
			if(address==null||address.trim().equals("")){
				String message = "请输入地址";
				renderJson("message",message);									
			}else{
			String message = "地址可用";
			renderJson("message",message);		
			}
		}else{
			String message = "地址已存在";
			renderJson("message",message);								
		}
		
	}
	
	/**
	 * 首页点赞
	 */
	public void searchPraise() {
		String shopId = getPara("shopid");
		String openid = getPara("openid");
		setAttr("serverUrl", getServer());
		UserShop us = UserShop.dao.findFirst("select * from ka_user_shop where shop_id=? and openid=?",shopId,openid);
		Praise p = Praise.dao.findFirst("select * from ka_pointpraise_set where shop_id=? and type=?",shopId,"点赞");
		int day_count = 0;
		int daycount = 0;
		int day_praise_count = 0;
		String total_count = "";
		int pointPraiseCount = 0;
		if(us!=null){
		if(us.getInt("point_praise_count")!=null){
			pointPraiseCount=us.getInt("point_praise_count");
		}
		}
		Shop shop = Shop.dao.findFirst("select * from ka_shop where id=?",shopId);
		if(shop.getStr("total_count")==null){
		total_count = "0";
		}else{
			total_count = shop.getStr("total_count");
		}
		int praise = Integer.parseInt(total_count)+1;
		String praise1= Integer.toString(praise);	
		if(p==null)
		{
			day_count = 0;
		}else{
			if(p.getInt("day_count")!=null){
			day_count = p.getInt("day_count");
			}
			
		}
		if(us!=null){
		if(us.getInt("day_praise_count")!=null){
			day_praise_count = us.getInt("day_praise_count");
		}
		}
		 daycount =day_count;
		  SimpleDateFormat format = new SimpleDateFormat("d"); 
		  Date d = new Date();
		  String date = format.format(d);	
		if(p!=null && !p.getStr("enabled").equals("关闭")){  
		if(us==null){
			if(daycount==0){
				String message = "不允许点赞";
				renderJson("message",message);
			}else if(openid!=null){
			UserShop u = new UserShop();
			shop.set("total_count", praise1).update();
			u.set("day_praise_count", day_praise_count+1).set("praise_time", date).set("point_praise_count", pointPraiseCount+1).set("id", System.currentTimeMillis() + "").set("openid", openid).set("shop_id", shopId).save();
			renderJson("praise1",praise);
			}else{
				String message = "不允许点赞";
				renderJson("message",message);				
			}
		}else{
			if(us.getStr("praise_time")!=null){
			if(us.getStr("praise_time").equals(date)){
				if(day_praise_count==daycount){
					String message = "今天已点赞";
					renderJson("message",message);
				}else{
				shop.set("total_count", praise1).update();
				us.set("day_praise_count", day_praise_count+1).set("praise_time", date).set("point_praise_count", pointPraiseCount+1).update();
				renderJson("praise1",praise1);
					}
			}else{
				day_praise_count=0;
				if(day_praise_count==daycount){
					String message = "今天已点赞";
					renderJson("message",message);
				}else{
				shop.set("total_count", praise1).update();
				us.set("day_praise_count", day_praise_count+1).set("praise_time", date).set("point_praise_count", pointPraiseCount+1).update();
				renderJson("praise1",praise1);
					}
			}
			}else{
				if(daycount==0){
					String message = "不允许点赞";
					renderJson("message",message);
				}else{
				shop.set("total_count", praise1).update();
				us.set("day_praise_count", day_praise_count+1).set("praise_time", date).set("point_praise_count", pointPraiseCount+1).update();
				renderJson("praise1",praise);
				}				
			}
		}
		}else{
			forwardAction("/shopIndex/"+shopId+"-"+openid);	
		}
	}
	
	/**
	 * 首页分享
	 */
	public void searchShare(){
		String shopId = getPara("shopid");
		String openid = getPara("openid");
		setAttr("serverUrl", getServer());
		UserShop us = UserShop.dao.findFirst("select * from ka_user_shop where shop_id=? and openid=?",shopId,openid);
		Praise s = Praise.dao.findFirst("select * from ka_pointpraise_set where shop_id=? and type=?",shopId,"分享");
		int day_count = 0;
		int daycount = 0;
		int day_share_count = 0;
		String total_count = "";
		int shareCount = 0;
		if(us!=null){
		if(us.getInt("share_count")!=null){
			shareCount=us.getInt("share_count");
		}
		}
		Shop shop = Shop.dao.findFirst("select * from ka_shop where id=?",shopId);
		if(shop.getStr("total_count1")==null){
		total_count = "0";
		}else{
			total_count = shop.getStr("total_count1");
		}
		int praise = Integer.parseInt(total_count)+1;
		String praise1= Integer.toString(praise);		
		if(s==null)
		{
			day_count = 0;
		}else{
			day_count = s.getInt("day_count");
		}
		if(us!=null){
		if(us.getInt("day_share_count")!=null){
			day_share_count = us.getInt("day_share_count");
		}
		}
			daycount =day_count;
		
		  SimpleDateFormat format = new SimpleDateFormat("d"); 
		  Date d = new Date();
		  String date = format.format(d);	
		if(us==null){
			if(daycount==0){
				String message = "不允许点赞";
				renderJson("message",message);
			}else{
			UserShop u = new UserShop();
			shop.set("total_count1", praise1).update();
			u.set("day_share_count", day_share_count+1).set("share_time", date).set("share_count", shareCount+1).set("id", System.currentTimeMillis() + "").set("openid", openid).set("shop_id", shopId).save();
			renderJson("praise1",praise);	
			}
		}else{
			if(us.getStr("share_time")!=null){
			if(us.getStr("share_time").equals(date)){
				if(day_share_count==daycount){
					String message = "今天已点赞";
					renderJson("message",message);
				}else{
				shop.set("total_count1", praise1).update();
				us.set("day_share_count", day_share_count+1).set("share_time", date).set("share_count", shareCount+1).update();
				renderJson("praise1",praise1);
					}
			}else{
				day_share_count=0;
				if(day_share_count==daycount){
					String message = "今天已点赞";
					renderJson("message",message);
				}else{
				shop.set("total_count1", praise1).update();
				us.set("day_share_count", day_share_count+1).set("share_time", date).set("share_count", shareCount+1).update();
				renderJson("praise1",praise1);
					}
			}
			}else{
				if(daycount==0){
					String message = "不允许点赞";
					renderJson("message",message);
				}else{
				shop.set("total_count1", praise1).update();
				us.set("day_share_count", day_share_count+1).set("share_time", date).set("share_count", shareCount+1).update();
				renderJson("praise1",praise);	
				}				
			}
		}
	}
	
	/**
	 * 子页点赞
	 */
	public void searchPraise1() {
		String shopId = getPara(0);
		String openid = getPara(1);
		setAttr("serverUrl", getServer());
		UserShop us = UserShop.dao.findFirst("select * from ka_user_shop where shop_id=? and openid=?",shopId,openid);
		Praise p = Praise.dao.findFirst("select * from ka_pointpraise_set where shop_id=? and type=?",shopId,"点赞");
		int day_count = 0;
		int daycount = 0;
		int day_praise_count = 0;
		String total_count = "";
		int pointPraiseCount = 0;
		if(us!=null){
		if(us.getInt("point_praise_count")!=null){
			pointPraiseCount=us.getInt("point_praise_count");
		}		
		}
		Shop shop = Shop.dao.findFirst("select * from ka_shop where id=?",shopId);
		if(shop.getStr("total_count")==null){
			total_count = "0";
			}else{
				total_count = shop.getStr("total_count");
			}				
		int praise = Integer.parseInt(total_count)+1;
		String praise1= Integer.toString(praise);		
		if(p==null)
		{
			day_count = 0;
		}else{
			day_count = p.getInt("day_count");
		}
		if(us!=null){
		if(us.getInt("day_praise_count")!=null){
			day_praise_count = us.getInt("day_praise_count");
		}
		}
		daycount =day_count;
		
		  SimpleDateFormat format = new SimpleDateFormat("d"); 
		  Date d = new Date();
		  String date = format.format(d);	
		if(p!=null && !p.getStr("enabled").equals("关闭")){    
		if(us==null){
			if(daycount==0){
				String message = "店家未开放点赞功能";
				forwardAction("/praise/"+shopId+"-"+openid+"-"+message);
				}else if(openid!=null){
			UserShop u = new UserShop();
			shop.set("total_count", praise1).update();
			u.set("day_praise_count", day_praise_count+1).set("praise_time", date).set("point_praise_count", pointPraiseCount+1).set("id", System.currentTimeMillis() + "").set("openid", openid).set("shop_id", shopId).save();
			forwardAction("/shopIndex/"+shopId+"-"+openid);	
			}else{
				String message = "店家未开放点赞功能";
				forwardAction("/praise/"+shopId+"-"+openid+"-"+message);
			}
		}else{
			if(us.getStr("praise_time")!=null){
			if(us.getStr("praise_time").equals(date)){
				if(day_praise_count==daycount){
					String message = "您今天点赞数已用完";
					forwardAction("/praise/"+shopId+"-"+openid+"-"+message);
					}else{
				shop.set("total_count", praise1).update();
				us.set("day_praise_count", day_praise_count+1).set("praise_time", date).set("point_praise_count", pointPraiseCount+1).update();
				String message = "点赞成功";
				forwardAction("/praise/"+shopId+"-"+openid+"-"+message);
					}
			}else{
				day_praise_count=0;
				if(day_praise_count==daycount){
					String message = "您今天点赞数已用完";
					forwardAction("/praise/"+shopId+"-"+openid+"-"+message);
				}else{
				shop.set("total_count", praise1).update();
				us.set("day_praise_count", day_praise_count+1).set("praise_time", date).set("point_praise_count", pointPraiseCount+1).update();
				String message = "点赞成功";
				forwardAction("/praise/"+shopId+"-"+openid+"-"+message);
					}
			}
			}else{
				if(daycount==0){
					String message = "店家未开放点赞功能";
					forwardAction("/praise/"+shopId+"-"+openid+"-"+message);
					}else{
				shop.set("total_count", praise1).update();
				us.set("day_praise_count", day_praise_count+1).set("praise_time", date).set("point_praise_count", pointPraiseCount+1).update();
				String message = "点赞成功";
				forwardAction("/praise/"+shopId+"-"+openid+"-"+message);
				}				
			}
		}
		}else{
			String message = "店家未开放点赞功能";
			forwardAction("/praise/"+shopId+"-"+openid+"-"+message);
		}
	}
	/**
	 * 子页分享
	 */
	public void searchShare1(){
		String shopId = getPara(0);
		String openid = getPara(1);
		setAttr("serverUrl", getServer());
		UserShop us = UserShop.dao.findFirst("select * from ka_user_shop where shop_id=? and openid=?",shopId,openid);
		Praise s = Praise.dao.findFirst("select * from ka_pointpraise_set where shop_id=? and type=?",shopId,"分享");
		int day_count = 0;
		int daycount = 0;
		int day_share_count = 0;
		String total_count = "";
		int shareCount = 0;
		if(us!=null){
		if(us.getInt("share_count")!=null){
			shareCount=us.getInt("share_count");
		}		
		}
		Shop shop = Shop.dao.findFirst("select * from ka_shop where id=?",shopId);
		if(shop.getStr("total_count1")==null){
			total_count = "0";
			}else{
				total_count = shop.getStr("total_count1");
			}				
		int praise = Integer.parseInt(total_count)+1;
		String praise1= Integer.toString(praise);		
		if(s==null)
		{
			day_count = 0;
		}else{
			day_count = s.getInt("day_count");
		}
		if(us!=null){
		if(us.getInt("day_share_count")!=null){
			day_share_count = us.getInt("day_share_count");
		}
		}
		daycount =day_count;
		
		  SimpleDateFormat format = new SimpleDateFormat("d"); 
		  Date d = new Date();
		  String date = format.format(d);	
		if(us==null){
			if(daycount==0){
				forwardAction("/shopIndex/"+shopId+"-"+openid);
				}else{
			UserShop u = new UserShop();
			shop.set("total_count1", praise1).update();
			u.set("day_share_count", day_share_count+1).set("share_time", date).set("share_count", shareCount+1).set("id", System.currentTimeMillis() + "").set("openid", openid).set("shop_id", shopId).save();
			forwardAction("/shopIndex/"+shopId+"-"+openid);
			}
		}else{
			if(us.getStr("share_time")!=null){
			if(us.getStr("share_time").equals(date)){
				if(day_share_count==daycount){
					forwardAction("/shopIndex/"+shopId+"-"+openid);
					}else{
				shop.set("total_count1", praise1).update();
				us.set("day_share_count", day_share_count+1).set("share_time", date).set("share_count", shareCount+1).update();
				forwardAction("/shopIndex/"+shopId+"-"+openid);
					}
			}else{
				day_share_count=0;
				if(day_share_count==daycount){
					forwardAction("/shopIndex/"+shopId+"-"+openid);
				}else{
				shop.set("total_count1", praise1).update();
				us.set("day_share_count", day_share_count+1).set("share_time", date).set("share_count", shareCount+1).update();
				forwardAction("/shopIndex/"+shopId+"-"+openid);
					}
			}
			}else{
				if(daycount==0){
					forwardAction("/shopIndex/"+shopId+"-"+openid);
					}else{
				shop.set("total_count1", praise1).update();
				us.set("day_share_count", day_share_count+1).set("share_time", date).set("share_count", shareCount+1).update();
				forwardAction("/shopIndex/"+shopId+"-"+openid);
				}
			}
		}
	}
	/**
	 * 点赞认领卡点
	 */	
	public void takePraisePoint(){
		String shopId = getPara(0);
		String openid = getPara(1);
		Praise p = Praise.dao.findFirst("select * from ka_pointpraise_set where shop_id=? and type=?",shopId,"点赞");
		UserShop us = UserShop.dao.findFirst("select * from ka_user_shop where openid=? and shop_id=?",openid,shopId);
		Order order = Order.dao.findFirst("select * from ka_order where openid=? and shop_id=?",openid,shopId);
		int point_praise_count =us.getInt("point_praise_count");
		int total_count =p.getInt("total_count");
		int use_point,count_point;
		if(us.getInt("use_point")==null){
			use_point=0;
		}else{
			use_point = us.getInt("use_point");
		}
		if(us.getInt("count_point")==null){
			count_point=0;
		}else{
			count_point = us.getInt("count_point");
		}		
		int presenter_count =p.getInt("presenter_count");
		if(point_praise_count/total_count>=1){
		us.set("point_praise_count", point_praise_count%total_count).set("use_point", use_point+point_praise_count/total_count*presenter_count).set("count_point", count_point+point_praise_count/total_count*presenter_count).set("operate", new Date()).update();
		Shop shop = Shop.dao.findById(shopId);
		Date date = new Date();
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.MONTH, Integer.parseInt(shop.getStr("valid_date")));
		Track track = new Track();
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
		track.set("id", System.currentTimeMillis() + "").set("nick_name", openid).set("create_date", new Date()).set("del_flag", "0").set("update_date", new Date()).set("create_date_str", format.format(new Date())).set("state", "0").set("count", point_praise_count/total_count*presenter_count).set("usable_count", point_praise_count/total_count*presenter_count).set("shop_id", shopId).set("valid_date", cal.getTime()).set("remarks", "认领点赞，获赠"+point_praise_count/total_count*presenter_count+"个卡点").set("create_name", "我自己").save();
		if(order!=null){
		order.set("time", new Date()).update();
		}
		forwardAction("/praise/"+shopId+"-"+openid+"-"+"认领成功，获得"+point_praise_count/total_count*presenter_count+"个卡点");
		}else{
			forwardAction("/praise/"+shopId+"-"+openid);	
		}
	}
	/**
	 * 分享认领卡点
	 */		
	public void takeSharePoint(){
		String shopId = getPara(0);
		String openid = getPara(1);
		Praise s = Praise.dao.findFirst("select * from ka_pointpraise_set where shop_id=? and type=?",shopId,"分享");
		UserShop us = UserShop.dao.findFirst("select * from ka_user_shop where openid=? and shop_id=?",openid,shopId);
		Order order = Order.dao.findFirst("select * from ka_order where openid=? and shop_id=?",openid,shopId);
		int share_count =us.getInt("share_count");
		int total_count =s.getInt("total_count");
		int use_point,count_point;
		if(us.getInt("use_point")==null){
			use_point=0;
		}else{
			use_point = us.getInt("use_point");
		}
		if(us.getInt("count_point")==null){
			count_point=0;
		}else{
			count_point = us.getInt("count_point");
		}				
		int presenter_count =s.getInt("presenter_count");
		if(share_count/total_count>=1){
		us.set("share_count", share_count%total_count).set("use_point", use_point+share_count/total_count*presenter_count).set("count_point", count_point+share_count/total_count*presenter_count).set("operate", new Date()).update();
		Shop shop = Shop.dao.findById(shopId);
		Date date = new Date();
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.MONTH, Integer.parseInt(shop.getStr("valid_date")));
		Track track = new Track();
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
		track.set("id", System.currentTimeMillis() + "").set("nick_name", openid).set("create_date", new Date()).set("del_flag", "0").set("update_date", new Date()).set("create_date_str", format.format(new Date())).set("state", "0").set("count", share_count/total_count*presenter_count).set("usable_count", share_count/total_count*presenter_count).set("shop_id", shopId).set("valid_date", cal.getTime()).set("remarks", "认领分享，获赠"+share_count/total_count*presenter_count+"个卡点").set("create_name", "我自己").save();		
		if(order!=null){
		order.set("time", new Date()).update();
		}	
		forwardAction("/share/"+shopId+"-"+openid+"-"+"认领成功，获得"+share_count/total_count*presenter_count+"个卡点");
		}else{
			forwardAction("/share/"+shopId+"-"+openid);	
		}
	}
	
	public void classtest(){
		setAttr("report", Report.dao.findById("1415342551732"));
		render("/test.jsp");
	}
}
